/**
 * 分页查询方法
 * @param url
 * @param pageNo
 * @param pageSize
 */
function submit(url, pageNo, pageSize) {
    if (pageNo === undefined) {
        pageNo = initPageNo;
    }
    if (pageSize === undefined) {
        pageSize = initPageSize;
    }

    layui.use(['table', 'laypage', 'form'], function () {
        let table = layui.table;
        let laypage = layui.laypage;
        // let loading = layer.msg('正在查询...', {icon: 16, shade: 0.3, time: 0});
        let sealCode = $('#sealCode').val();
        let keyWords = $('#keyWords').val();
        let orgName = $('#orgName').val();
        let sealSource = $('#sealSource').val();
        let channelNo = $('#channelNo').val();
        let channelName = $('#channelName').val();
        let channelMappingNo = $('#channelMappingNo').val();

        //第一个实例
        table.render({
            elem: '#searchTable',
            url: url,
            page: false,
            toolbar: '#tableToolbar',
            method: 'POST',
            height: 'full-250',
            headers: {"token": getCookie("token")},
            contentType: "application/json",
            where: {
                sealCode: sealCode,
                keyWords: keyWords,
                orgName: orgName,
                channelNo: channelNo,
                channelName: channelName,
                sealSource: sealSource,
                channelMappingNo: channelMappingNo,
                pageNo: pageNo,
                pageSize: pageSize
            }
            ,
            cols: [[
                {type: 'numbers', align: 'center'}
                , {field: 'sealCode', title: '印章编码', width: '250', align: 'center'}
                , {field: 'sealName', title: '印章名称', width: '250', align: 'center'}
                , {field: 'statusName', title: '印章状态', width: '100', align: 'center'}
                , {
                    field: 'createTime', title: '创建时间', width: '200', align: 'center', templet: function (d) {
                        return toDateString(d.createTime);
                    }
                }
                , {field: 'sealOrg', title: '企业名称', width: '250', align: 'center'}
                , {field: 'identificationTypeName', title: '证件类型', width: '200', align: 'center'}
                , {field: 'identificationNo', title: '证件号码', width: '200', align: 'center'}
                , {field: 'officeSealTypeName', title: '公章类型', width: '150', align: 'center'}
                , {field: 'sealSourceName', title: '公章来源', width: '150', align: 'center'}
                , {fixed: 'right', width: '200', title: '操作', align: 'center', toolbar: '#barSearch'} //添加工具条,
            ]]
            ,
            parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.pageInfo.totalCount, //解析数据长度
                    "pageNo": res.data.pageInfo.pageNo, //解析数据长度
                    "pageSize": res.data.pageInfo.pageSize, //解析数据长度
                    "data": res.data.pageInfo.list //解析数据列表
                };
            }
            , done: function (res) {
                // layer.close(loading);
                //校验登陆状态
                checkLogin(res);
                //增加自定义样式
                beautyCell();
                hideAddButton(res);
                //自定义分页
                laypage.render({
                    elem: 'tablePage'
                    , curr: res.pageNo
                    , count: res.count
                    , limit: res.pageSize
                    , layout: ['page', 'limit', 'count', 'skip']
                    , theme: '#1b2b34'
                    , jump: function (obj, first) {
                        if (!first) {
                            submit(url, obj.curr, obj.limit);
                        }
                    }
                });
            }
            , error: function () {
                layer.close(loading);
            }
        });

        //工具条
        table.on('tool(searchTable)', function (obj) {
            let data = obj.data;
            if (obj.event === 'detail') {
                let id = data.id;
                let appId = data.appId;
                xadmin.open("印章信息", "./look.html?id=" + id + "&appId=" + appId, 680, 520);
            }
            if (obj.event === 'updateSts') {
                let status = data.status;
                let sealCode = data.sealCode;
                let id = data.id;
                let msg;
                let confirmStatus;
                if (status === 1) {
                    msg = "确定要停用吗？";
                    confirmStatus = 0;
                } else {
                    msg = "确定要启用吗？";
                    confirmStatus = 1;
                }
                layer.confirm(msg, {icon: 3, title: '修改状态'}, function (index) {
                    updateStatus(confirmStatus, sealCode, id, index);
                });
            }
        });

        //头部按钮
        table.on('toolbar(searchTable)', function (obj) {
            let checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'create':
                    xadmin.open("新增印章", "./add.html", 480, 550);
                    break;
                case 'create2':
                    xadmin.open("新增印章", "./add2.html", 480, 500);
                    break;
                case 'export':
                    let data = checkStatus.data;
                    let ids = [];
                    $.each(data, function (i, item) {
                        ids.push(item.refId);
                    });
                    exportTemplate(ids);
                    break;
            }
        })

    });
}


/**
 * 隐藏添加按钮
 */
function hideAddButton(res) {
    var obj = res.data[0];
    if(obj.appId != null || obj.appId != undefined){
        $('#zjBtn').hide();
    }else {
        $('#fddBtn').hide();
    }
}


/**
 * 文件上传
 */
function uploadFile(upload, uploadUrl) {
    upload.render({
        elem: '#uploadImage'
        , url: uploadUrl
        , accept: 'images'
        , size: '1024'
        , exts: "png"
        , headers: {'token': getCookie('token')}
        , done: function (res) {
            if (res.code === 0) {
                $('#pictureId').val(res.data.pictureId);
                $("#fileName").html(res.data.fileName)
                alert("上传成功！")
            } else {
                errorMsg("文件上传失败！")
            }
        }
    });
}

/**
 * 查询证书类型
 * @param form
 */
function queryCertType(form) {
    let url = serverPre + "/manager/scs/v2/sealInfo/certType/list";
    let content = '<option value="">证件类型</option>'; //全局变量
    let data = JSON.stringify({'pageNo': '1', 'pageSize': '999'});
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                let result = res.data.list;
                $.each(result, function (i, item) {
                    let certType = item.code;
                    let certTypeName = item.name;
                    content += '<option value = "' + certType + '">' + certTypeName + '</option>'
                });
                $("#identificationType").html(content);
                form.render('select');
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}


function queryPersonCertType(form) {
    let url = serverPre + "/manager/scs/v2/sealInfo/certType/list/p";
    let content = '<option value="">证件类型</option>'; //全局变量
    let data = JSON.stringify({'pageNo': '1', 'pageSize': '999'});
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                let result = res.data.list;
                $.each(result, function (i, item) {
                    let certType = item.code;
                    let certTypeName = item.name;
                    content += '<option value = "' + certType + '">' + certTypeName + '</option>'
                });
                $("#legalPersonCardType").html(content);
                form.render('select');
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}


/**
 * 修改公章状态
 * @param confirmStatus
 */
function updateStatus(confirmStatus, sealCode, id, index) {
    let url = serverPre + "/manager/scs/v2/sealInfo/updateSts";
    let data = JSON.stringify({'status': confirmStatus, 'sealCode': sealCode, 'id': id});
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                layer.close(index);
                $(".layui-laypage-btn")[0].click();
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}

/**
 * 根据证件类型证件号码查询公章信息
 * @param form
 */
function sealTypeAndIdNoListener(form) {
    form.on('select(identificationType)', function (data) {
        //判断证件号码是否为空
        var identificationNo = $('#identificationNo').val();
        if (identificationNo != "") {
            let reqData = JSON.stringify({'identificationType': data.value, 'identificationNo': identificationNo});
            $.ajax({
                url: serverPre + "/manager/scs/v2/sealInfo/querySealInfo",
                data: reqData,
                type: 'POST',
                contentType: 'application/json',
                headers: {'token': getCookie('token')},
                success: function (res) {
                    if (res.code === 0) {
                        if(res.data != null){
                            var obj = res.data;
                            buildOrgAndKeyWords(obj,form);
                        }
                    }
                }
            });
        }
    });

    $("#identificationNo").on("input", function (e) {
        //判断证件类型是否为空
        var identificationType = $('#identificationType').val();
        if (identificationType != "") {
            //获取input输入的值
            var identificationNo = e.delegateTarget.value;
            let reqData = JSON.stringify({'identificationType': identificationType, 'identificationNo': identificationNo});
            $.ajax({
                url: serverPre + "/manager/scs/v2/sealInfo/querySealInfo",
                data: reqData,
                type: 'POST',
                contentType: 'application/json',
                headers: {'token': getCookie('token')},
                success: function (res) {
                    if (res.code === 0) {
                        if(res.data != null){
                            var obj = res.data;
                            buildOrgAndKeyWords(obj,form);
                        }
                    }
                }
            });
        }
    });
}

/**
 * 封装企业名称和关键字
 * @param obj
 */
function buildOrgAndKeyWords(obj,form) {
    if(obj.vo != null){
        $('#sealOrg').val(obj.vo.sealOrg);
        $('#keyWords').val(obj.vo.keyWords);
        $('#sealCode').val(obj.vo.sealCode);
        $("#sealOrg").attr("readOnly",true);
        $("#keyWords").attr("readOnly",true);
        $("#pictureId").parent().parent().hide();
        form.render();
    }else {
        $("#sealOrg").attr("readOnly",false);
        $("#keyWords").attr("readOnly",false);
        $("#pictureId").parent().parent().show();
        $('#sealCode').val("");
        form.render();
    }
}


/**
 * 美化按钮样式
 */
function beautyCell() {
    $("[data-field='statusName']").children().each(function (index, item) {
        // debugger
        if (item.textContent === '启用') {
            $(this).css("color", "#228b22");
        }
        if (item.textContent === '停用') {
            $(this).css("color", "#ff0000");
        }
    })
}

/**
 * 查看窗口
 * @param result
 */
function buildOpenWin(result) {
    if (result === undefined || result === null) {
        errorMsg("返回数据为空");
    }
    if (result.sealName !== "") {
        $('#sealName').val(result.sealName);
    }
    if (result.sealCode !== "") {
        $('#sealCode').val(result.sealCode);
    }
    if (result.sealPwd !== "") {
        $('#sealPwd').val(result.sealPwd);
    }
    if (result.identificationTypeName !== "") {
        $('#identificationTypeName').val(result.identificationTypeName);
    }
    if (result.officeSealTypeName !== "") {
        $('#officeSealTypeName').val(result.officeSealTypeName);
    }
    if (result.createTime !== "") {
        let time = toDateString(result.createTime);
        $('#createTime').val(time);
    }
    if (result.identificationNo !== "") {
        $('#identificationNo').val(result.identificationNo);
    }
    if (result.keyWords !== "") {
        $('#keyWords').val(result.keyWords);
    }
    if (result.image !== "") {
        $("#sealImg").attr('src', 'data:image/png;base64,' + result.image);
    }
}


/**
 * 提交表单
 * @param formData
 * @param url
 */
function submitForm(commitData, url) {
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form;
        //监听提交
        form.on('submit(submitBtn)', function (data) {
            //判断图片是否为空--规则，因为如果根据证件类型和证件号码查询到数据，
            // sealCode会自动赋值并隐藏，所有判断sealCode是否为空则推断出是否为需要调三方，此时图片不能为空
            var customSealCode = $("input[name='customSealCode']:checked").val();
            var sealCode = $('#sealCode').val();
            var pictureId = $('#pictureId').val();
            if(customSealCode == '1'){
                if(sealCode === ""){
                    if (data.field.pictureId === "") {
                        alert("印章编码不能为空!");
                        return false;
                    }
                }
            }
            //判断图片是否存在
            let isHide = $("#pictureId").parent().parent().is(":hidden");
            if(isHide == false){
                if(pictureId === ""){
                    if (data.field.pictureId === "") {
                        alert("公章图片不能为空!");
                        return false;
                    }
                }
            }
            saveSealInfo(url, commitData);
        });
    })
}

/**
 * 保存印章
 * @param url
 * @param commitData
 */
function saveSealInfo(url, commitData) {
    let loading = layer.msg('正在制章...', {icon: 16, shade: 0.3, time: 0});
    $.ajax({
        url: url,
        data: commitData,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            layer.close(loading);
            if (res.code === 0) {
                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                layer.close(index);
                parent.location.reload();
            } else {
                alert(res.msg);
            }
        }
    });
}

/**
 * 动态补全input框内容
 */
function autocompleteName() {
    $("#sealName").autocomplete({
        source: function (request, response) {
            // request对象只有一个term属性，对应用户输入的文本
            // response在你自行处理并获取数据后，将JSON数据交给该函数处理，以便于autocomplete根据数据显示列表
            let commitData = JSON.stringify({"sealName": request.term});
            $.ajax({
                url: serverPre + "/manager/scs/v2/sealInfo/searchSealName",
                type: "post",
                dataType: "json",
                contentType: 'application/json',
                headers: {'token': getCookie('token')},
                data: commitData,  // 获取输入框内容
                success: function (res) {
                    response($.map(res.data.list, function (item) { // 此处是将返回数据转换为 JSON对象
                        return {
                            label: item.sealName, // 下拉项显示内容
                            value: item.sealName  // 下拉项对应数值
                        }
                    }));
                }
            });
        },
        select: function (event, ui) { //event参数是事件对象，ui对象只有一个item属性，对应数据源中被选中的对象
            $("#sealName").val(ui.item.value);
            return false;
        }
    });
}

/**
 * 不全sealcode
 */
function autocompleteCode(form) {
    let identificationNo = $("#identificationNo").val();
    let identificationType = $("#identificationType").val();
    let reqData = JSON.stringify({'identificationType': identificationType, 'identificationNo': identificationNo});
    $.ajax({
        url: serverPre + "/manager/scs/v2/sealInfo/querySealInfo",
        data: reqData,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                if(res.data != null){
                    var obj = res.data;
                    buildOrgAndKeyWords(obj,form);
                }
            }
        }
    });
}
